<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 添加角色按钮区 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
                </el-col>
            </el-row>

            <!-- 角色列表 -->
            <el-table :data="roleList" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                      <el-row :class="['bdbottom',i1 ===0 ? 'bdtop':'','vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
                          <!-- 渲染一级权限 -->
                          <el-col :span="5">
                             <el-tag closable @close="removeRightById(scope.row, item1)"> {{item1.authName}}</el-tag>
                             <i class="el-icon-caret-right"></i>
                          </el-col>
                          <!-- 渲染二级和三级权限 -->
                          <el-col :span="19">
                              <el-row :class="[i2 === 0 ? 'bdtop':'', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                                  <el-col :span="6">
                                    <el-tag type="success" closable @close="removeRightById(scope.row, item2)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                  </el-col>
                                  <el-col :span="18">
                                      <el-tag type="warning" v-for="(item3, i3) in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3)">{{item3.authName}}</el-tag>
                                  </el-col>
                              </el-row>
                          </el-col>
                      </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" >
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRoles(scope.row.id)">删除</el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色对话框 -->
        <el-dialog
        title="添加角色"
        :visible.sync="addDialogVisible"
        width="50%" @close="addDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesFormRef" label-width="70px">
                <el-form-item label="添加角色名称" prop="roleName">
                    <el-input v-model="addRolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="添加角色描述" prop="roleDesc">
                    <el-input v-model="addRolesForm.roleDesc"></el-input> 
                </el-form-item>  
            </el-form>
            <!-- 底部区 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改角色的对话框 -->
        <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%" @close="editDialogClosed">
            <el-form :model="editRolesForm" :rules="addRolesFormRules" ref="editRolesFormRef" label-width="70px">
                <el-form-item label="角色">
                    <el-input v-model="editRolesForm.roleName" disabled></el-input>
                </el-form-item>
                <el-form-item label="描述" prop= "roleDesc">
                    <el-input v-model="editRolesForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRolesInfo">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限对话框 -->
        <!-- 修改角色的对话框 -->
        <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="50%" @close="setRightDialogClosed">
            <!-- 树形控件 -->
            <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // 所有角色列表数据
            roleList:[],
            // 控制添加角色对话框显示
            addDialogVisible: false,
            // 控制修改角色对话框显示
            editDialogVisible: false,
            // 添加角色的表单数据
            addRolesForm: {
                roleName: '',
                roleDesc: '',
            },
            // 修改角色表单查询数据
            editRolesForm: {

            },
            // 添加角色表单验证
            addRolesFormRules:{
                 roleName:[
                     {required: true, message: '请输入添加角色名称', trigger: 'blur'},
                     {min:3, max: 7, message: '密码长度在3-7个字符', trigger: 'blur'}
                ],
                roleDesc:[
                     {required: true, message: '请输入添加角色描述', trigger: 'blur'},
                     {min:3, max: 10, message: '密码长度在3-10个字符', trigger: 'blur'}
                ]
            },
            // 修改权限对话框显示
            setRightDialogVisible: false,
            // 修改权限数据
            rightsList: {

            },
            // 树形控件属性绑定对像
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            // 默认节点选中ID值数组
            defKeys: [],
            roleId: '',
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        async getRolesList() {
            const {data:res} = await this.$http.get('roles')
            if(res.meta.status !== 200){
                return this.$message.error('获取角色列表失败')
            }
            this.roleList = res.data
        },
        // 监听添加角色对话框关闭事件
        addDialogClosed() {
            this.$refs.addRolesFormRef.resetFields()
        },
        // 监听修改角色对话框关闭事件
        editDialogClosed() {
            this.$refs.editRolesFormRef.resetFields()
        },
        // 添加角色
        addRoles() {
            this.$refs.addRolesFormRef.validate(async valid =>{
                if(!valid) return
                const {data:res} = await this.$http.post('roles', this.addRolesForm)
                if(res.meta.status !== 201) {
                    return this.$message.error('添加角色失败！')
                }
                this.$message.success('添加用户成功')
                this.addDialogVisible = false 
                this.getRolesList()
            })
        },
        // 修改角色按钮id查询
        async showEditDialog(id) {
            const {data: res} = await this.$http.get('roles/' + id)
            if(res.meta.status !==200){
                return $message.error("查询角色信息失败")
            }
            this.editRolesForm = res.data;
            this.editDialogVisible = true;
        },
        // 修改角色提交
        editRolesInfo(){
            this.$refs.editRolesFormRef.validate(async valid =>{
                if(!valid) return
                const {data:res} = await this.$http.put('roles/' + this.editRolesForm.roleId, {
                    roleName: this.editRolesForm.roleName,
                    roleDesc: this.editRolesForm.roleDesc
                })
                if(res.meta.status !== 200) {
                    return this.$message.error("编辑角色失败")
                }
                this.$message.success("编辑角色成功")
                this.editDialogVisible = false
                this.getRolesList()
            })

        },
        // 删除角色按钮
        async removeRoles(id) {
            const confirmResult = await this.$confirm('此操作将永久删除该角色，是否继续', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error => error)

            if(confirmResult!=='confirm'){
                return this.$message.info('已取消删除')
            }
            // 删除用户信息
            const {data: res} = await this.$http.delete('roles/' + id)
            if(res.meta.status !==200) {
                return this.$message.error('用户删除失败')
            }
            this.$message.success('用户删除成功')
            this.getRolesList()
        },
        // 修改权限
        async removeRightById(role, right) {
            const confirmResult = await this.$confirm('此操作会永久删除该角色权限', '提示',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)

            if(confirmResult!=='confirm'){
                return this.$message.info('已取消删除')
            }
            // 删除用户信息
            const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${right.id}`)
            if(res.meta.status !==200) {
                return this.$message.error('权限删除失败')
            }
            this.$message.success('用户删除成功')
            role.children = res.data
        },
        // 展示分配权限的对话框
        async showSetRightDialog(role) {
            this.roleId = role.id
            // 获取权限数据
            const {data:res} = await this.$http.get('rights/tree')
            if(res.meta.status !== 200) {
                return this.$message.error('获取权限数据失败')
            }
            this.rightsList = res.data
            this.getLeafKeys(role, this.defKeys)
            this.setRightDialogVisible = true
        },
        // 通过递归的形式获取角色下所有三级权限的id，并保存defkeys
        getLeafKeys(node, arr) {
            if(!node.children){
                return arr.push(node.id)
            }
            node.children.forEach(item =>{
                this.getLeafKeys(item, arr)
            })
        },
        // 监听权限
        setRightDialogClosed() {
            this.defKeys = []
        },
        async allotRights() {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = keys.join(',')
            const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
            if(res.meta.status !==200){
                return this.$message.error('分配权限失败')
            }
            this.$message.success('分配权限成功')
            this.getRolesList()
            this.setRightDialogVisible = false
        }
    },
}
</script>

<style lang="less" scoped>
    .el-tag {
        margin: 7px;
    }
    .bdtop{
        border-top: 1px solid #eee;
    }
    .bdbottom {
        border-bottom: 1px solid #eee;
    }
    .vcenter {
        display: flex;
        align-items: center;
    }
</style>